"""
Everything related to how display models when accessing some URLs
"""
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.db import transaction

from cassebras.contest.models import Competitor, Category, Slope

from cassebras.contest.forms import CompetitorForm

# * Use the commit_on_success  decorator to use a single transaction 
#   for all the work done in a function
#
# * Use the login_required decorator to limit access to only logged-in users.
@login_required
@transaction.commit_on_success
def edit_competitor(request, competitor_id):
    """
    Method called when accessing ./competitors/$competitor_id URL
    """
    _competitor = get_object_or_404(Competitor, number=competitor_id)
    saved = False
    if request.method == 'POST':
        comp_form = CompetitorForm(request.POST, instance=_competitor)
        if comp_form.is_valid():
            _climbed_slopes = comp_form.cleaned_data['climbed_slopes']
            _competitor.update_climbed_slopes(_climbed_slopes)
            _competitor.update_score()
            competitor_obj = Competitor.objects.all().filter(id=_competitor.id)
            competitor_obj.update(name=comp_form.cleaned_data['name'])
            competitor_obj.update(surname=comp_form.cleaned_data['surname'])
            competitor_obj.update(category=comp_form.cleaned_data['category'])
            return HttpResponseRedirect(reverse('category', args=[_competitor.category.id]))
            # return HttpResponseRedirect(reverse(_competitor.category.url()))
    else:
        comp_form = CompetitorForm(instance=_competitor)
    return render_to_response(  'contest/competitor.html', 
                                { 'competitor_form': comp_form, 
                                  'competitor': _competitor,
                                  'saved': saved}
                             )

def show_contest(request):
    """
    Display ranking of all categories of the contest
    """
    _categories = Category.objects.all()
    _slopes = Slope.objects.all().order_by('-score')
    return render_to_response(  'contest/contest.html', 
                             {'categories': _categories, 
                              'slopes': _slopes})


from cassebras.contest.search import normalize_query, get_query
def search(request):
    query = request.GET.get('q', '')
    if query:
        qset = get_query(query, ['name', 'surname', 'number', ])
        results = Competitor.objects.filter(qset).distinct()
    else:
        results = []
    return render_to_response("contest/search.html", {
                              "competitors": results,
                              "query": query}
                              )
 